
import { _decorator, Component, Node, Prefab, instantiate, Intersection2D, math, UITransform, director } from 'cc';
import NodeX from './NodeX';
import { SpatialHash } from './SpatialHash';
import { LoopCount } from './Constants';
const { ccclass, property } = _decorator;



@ccclass('CompareHash')
export class CompareHash extends Component {
    @property(Prefab)
    nodePrefab: Prefab | null = null;
    private nodes: Array<Node> = [];

    private hash: SpatialHash = new SpatialHash(50);


    start() {
        // [3]
        for (let i = 0; i < LoopCount; i++) {
            let newNode = instantiate(this.nodePrefab);
            this.node.addChild(newNode);
            this.nodes.push(newNode);
        }
    }

    update(deltaTime: number) {
        this.hashCheck();
    }


    hashCheck() {
        for (let i in this.nodes) {
            let node = this.nodes[i]
            node.getComponent(NodeX).setIsCollision(false);
            this.nodes[i].getComponent(NodeX).setIsCollision(false);
            this.hash.insert(node);

        }

        for (let i in this.nodes) {
            let node = this.nodes[i];
            let list = this.hash.query(node);

            for (const targetNode of list) {
                if (targetNode === node) continue
                let isCollision: boolean = this.isCollision(targetNode, node)
                if (isCollision) {
                    node.getComponent(NodeX).setIsCollision(isCollision)
                    targetNode.getComponent(NodeX).setIsCollision(isCollision)
                }
            }
        }
        this.hash.clear();
    }

    onClickOpen() {
        director.loadScene("main");
    }
    isCollision(node1: Node, node2: Node) {
        let nodePos1 = node1.getPosition();
        let nodePos2 = node2.getPosition();
        let node1Left = nodePos1.x;
        let node2Left = nodePos2.x;
        let nodeTrans1 = node1.getComponent(UITransform);
        let nodeTrans2 = node2.getComponent(UITransform);
        let node1Top = nodePos1.y - nodeTrans1.height;
        let node2Top = nodePos2.y - nodeTrans2.height;

        return node1Left < node2Left + nodeTrans2.width &&
            node1Left + nodeTrans1.width > node2Left &&
            node1Top < node2Top + nodeTrans2.height &&
            node1Top + nodeTrans1.height > node2Top
    }


    isCollision2(node1: Node, node2: Node) {
        const nodeI = node1.getComponent(UITransform).getBoundingBoxToWorld();
        const nodeJ = node2.getComponent(UITransform).getBoundingBoxToWorld();

        return nodeI.intersects(nodeJ);
    }
}

